package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.config.exception.DataException;
import com.hljx.dto.SysDicItItemDTO;
import com.hljx.dto.SysDictPageDTO;
import com.hljx.entity.SysAccountingUnit;
import com.hljx.entity.SysDictItem;
import com.hljx.excel.ExcelTransfer;
import com.hljx.mapper.sys.SysDictItemMapper;
import com.hljx.service.SysAccountingUnitService;
import com.hljx.service.SysDictItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.vo.SysDictItemVO;
import com.hljx.vo.SysDictVO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 字典项 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-18
 */
@Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {

    @Autowired
    SysAccountingUnitService accountingUnitService;

    @Autowired
    private ExcelTransfer<SysDictItemVO> excelTransfer;

    @Autowired
    private ExcelTransfer<SysDictItem> dictItemExcelTransfer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateDictItem(SysDicItItemDTO dto) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getCode, dto.getCode())
                    .eq(SysDictItem::getDictId,dto.getDictId()).ne(dto.getId() != null, SysDictItem::getId, dto.getId()));
        if(count>0){
            throw new DataException("字典编码重复",201);
        }

        long result = baseMapper.selectCount(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getName,dto.getName())
                     .eq(SysDictItem::getDictId,dto.getDictId()).ne(dto.getId() != null, SysDictItem::getId, dto.getId()));

        if(result>0){
            throw new DataException("字典名称重复",201);
        }
        SysDictItem sysDictItem = new SysDictItem();
        BeanUtil.copyProperties(dto,sysDictItem);
        return saveOrUpdate(sysDictItem);
    }

    @Override
    public Boolean deleteDictItem(Long id) {
        long count = accountingUnitService.count(new LambdaQueryWrapper<SysAccountingUnit>().eq(SysAccountingUnit::getDictItemId, id));
        if(count>0){
            throw new DataException("该字典数据项被核算单元管理引用，无法删除",201);
        }
        return removeById(id);
    }

    @Override
    public Boolean updateDictItemStatus(Long id, Integer status) {
        return update(new LambdaUpdateWrapper<SysDictItem>().eq(SysDictItem::getId,id).set(SysDictItem::getStatus,status));

    }

    @Override
    public IPage<SysDictItemVO> listSysDictItemByPage(SysDictPageDTO dto) {
        Page<SysDictItemVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return baseMapper.listSysDictItemByPage(page, dto);
    }

    @Override
    public void export(SysDictPageDTO dto, HttpServletResponse response) throws ClassNotFoundException {
        List<SysDictItemVO> list = new ArrayList<>();
        if (dto.getType() == null) {
            throw new DataException("入参数据为空",201);
        }
        if (dto.getType() == 1) {
            Page<SysDictItemVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
            IPage<SysDictItemVO> iPage = baseMapper.listSysDictItemByPage(page, dto);
            list = iPage.getRecords();
        }
        excelTransfer.exportExcel(response, list, "字典数据项", "sheet1", SysDictItemVO.class);

    }

    @Override
    public void importExcel(Long dictId,MultipartFile file, HttpServletResponse response) throws ClassNotFoundException, IOException {
        List<SysDictItem> list = list(Wrappers.lambdaQuery(SysDictItem.class));
        dictItemExcelTransfer.importExcel(file, this, lists -> {
            ArrayList<SysDictItem> arrayList = new ArrayList<>();
            lists.forEach(e -> {
                if (list.stream().noneMatch(l -> e.getName().equals(l.getName())) || list.stream().noneMatch(l -> e.getCode().equals(l.getCode())) ) {
                    e.setStatus("是".equals(e.getEnable()) ? 1 : 0);
                    e.setDictId(dictId);
                    arrayList.add(e);
                }
            });
            return arrayList;
        });
    }
}
